<template>
  <div>
    <!-- 树形组件 -->
    <div class="my-tree">
      <!-- :show-checkbox="true" -->
      <el-tree
        ref="treeRef"
        :data="list"
        :props="{label:'name'}"
        :show-checkbox="true"
        :check-strictly="true"
        node-key="id"
        @node-click="handleNodeClick"
      />
    </div>
    <!-- 按钮 -->
    <div class="permission-btns">
      <el-button type="primary" round @click="onSubmit">确定</el-button>
      <el-button round @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getAllPermissionRequest } from '@/api/permission'
import { transformListToTree2 } from '@/utils'
import { getRoleDetailByIdRequest, assignPermRequest } from '@/api/setting'
export default {
  props: {
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getAllPermission()
    this.getRoleDetailById()
  },
  methods: {
    handleNodeClick(val) {
      console.log(val)
    },
    async getAllPermission() {
      try {
        const res = await getAllPermissionRequest()
        console.log('getAllPermissionRequest: ', res)
        if (res.success) {
          this.$message.success(res.message)
          this.list = transformListToTree2(res.data, '0')
          console.log('树形结构', this.list)
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('getAllPermissionRequest: ', err)
      }
    },
    // 根据id获取详细用户权限
    async getRoleDetailById() {
      try {
        const res = await getRoleDetailByIdRequest(this.currentId)
        console.log('getRoleDetailByIdRequest: ', res)
        if (res.success) {
          this.$message.success(res.message)
          this.$refs.treeRef.setCheckedKeys(res.data.permIds || [])
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('getRoleDetailByIdRequest: ', err)
      }
    },
    async assignPerm() {
      try {
        const res = await assignPermRequest({
          id: this.currentId,
          permIds: this.$refs.treeRef.getCheckedKeys()
        })
        console.log('assignPermRequest: ', res)
        if (res.success) {
          this.$message.success(res.message)
          this.cancel()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('assignPermRequest: ', err)
      }
    },
    onSubmit() {
      this.assignPerm()
    },
    cancel() {
      this.$emit('close')
    }
  }
}
</script>
